<?php
	class Thumbnail{
	
		private $image;
	//	private $quality = 100;
		private $dir = "../../img/product/";			// выставить дир как надо
		private $mimetype;
		private $imageproperties;
		
		public function __construct ($file_arr, $thumbNailSize = 100){
			$file = $file_arr['tmp_name'];
			$file_name = $file_arr['name'];
			$this->imageproperties = getimagesize($file) or die ("Invalid file type");
			$this->mimetype = $this->imageproperties['mime'];
			
			switch ($this->imageproperties['mime']){
				case "image/jpeg":
				$this->image = imagecreatefromjpeg($file);
				break;
				
				case "image/gif":
				$this->image = imagecreatefromgif($file);
				break;
				
				case "image/png":
				$this->image = imagecreatefrompng($file);
				break;
				
				default:
				die ("Can't create an image");
			}
			
			$this->createThumb($thumbNailSize);
			$this->getthumb($file_name);
		}

		private function createThumb($thumbNailSize){
			$srcW = $this->imageproperties[0];
			$srcH = $this->imageproperties[1];
			if($srcW > $thumbNailSize || $srcH > $thumbNailSize){
				$reduct = $this->calculateReduction($thumbNailSize);
				$desW = $srcW/$reduct;											//mbb
				$desH = $srcH/$reduct;
				$desW = round($desW);
				$desH = round($desH);
				$copy = imagecreatetruecolor($desW, $desH);
				imagecopyresampled($copy, $this->image, 0, 0, 0, 0, $desW, $desH, $srcW, $srcH) or die ("Image copy error");
				imagedestroy($this->image);
				$this->image = $copy;
			}
		}

		private function calculateReduction($thumbNailSize){
			$srcW = $this->imageproperties[0];
			$srcH = $this->imageproperties[1];
			if ($srcH > $srcW){
				$reduct = round($srcH/$thumbNailSize);  
			}
			else{
				$reduct = round($srcW/$thumbNailSize);
			}
			return $reduct;
		}
		
		private function getthumb($file_name){
			switch ($this->imageproperties['mime']){
			case "image/jpeg":
			imagejpeg($this->image, $this->dir.$file_name) or die("Nope");     					// Для png и jpeg 3 параметром можно менять качество
			break;
			
			case IMAGETYPE_PNG:
			imagepng($this->image, "", $this->quality);
			break;
			
			case IMAGETYPE_GIF:
			imagegif($this->image);
			break;
			
			default:
			die ("Can't create an image");
			}
		}
	/*	
		public function getmimetype(){
			return $this->mimetype;
		}
*/
/*
		public function setQuality($quality){
			if ($quality > 100 || $quality < 1){
				$quality = 75;
			}
			if ($this->imageproperties[2] == IMAGETYPE_JPEG){       	//mbb
				$this->quality = $quality;
			}
		}
*/		
		public function __destruct(){
			if (isset($this->image)){
				imagedestroy($this->image);
			}
		}
	}

?>